import { createRouter, createWebHistory } from "vue-router";
import { userCounter } from "@/stores/counter";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/admin",
      name: "admin",
      redirect: "/admin/login",
      meta: {
        title: "后台",
      },
      children: [
        {
          path: "/admin/login",
          name: "login",
          component: () => import("../views/admin/login/index.vue"),
          meta: {
            title: "登录",
          },
        },
        {
          path: "/admin/layout",
          name: "layout",
          component: () => import("../views/admin/layout/index.vue"),
          meta: {
            title: "首页",
          },
          children: [
            {
              path: "/admin/user",
              name: "user",
              component: () => import("../views/admin/layout/user/index.vue"),
              meta: {
                title: "用户管理",
              },
            },
            {
              path: "/admin/classify",
              name: "classify",
              component: () => import("../views/admin/layout/classify/index.vue"),
              meta: {
                title: "分类管理",
              },
            },
          ],
        },
      ],
    },
  ],
});

router.beforeEach(async (to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title;
  } else {
    document.title = "blog";
  }
  let token = userCounter().token;
  if (to.path === "/admin/login") {
    next();
  } else {
    token ? next() : next("/admin/login");
  }
  next();
});

export default router;
